import Koa from 'koa'
import path from 'path'
import koaBody from 'koa-body'
import logger from 'koa-logger'
// import user from './router/user'
import routing from './router/index'
import jwtKoa from 'koa-jwt'
import './dbHelper'
import responseFilter from './middleware/responseFilter'
import parameter from 'koa-parameter'
import koaStatic from 'koa-static'
import error from 'koa-json-error'
import { jwtConfig } from './config/index'
import { koaSwagger } from 'koa2-swagger-ui'
import swagger from './config/swagger'
import cheackShop from './middleware/cheackShop'
import cheackAiUser from './middleware/cheackAiUser'
import adminUser from './middleware/adminUser'

// import ratelimit from 'koa-ratelimit'
const app = new Koa()

process.env.NODE_ENV === 'development' ||
	(process.env.NODE_ENV === 'test' &&
		app.use(swagger.routes(), swagger.allowedMethods()))
process.env.NODE_ENV === 'development' ||
	(process.env.NODE_ENV === 'test' &&
		app.use(
			koaSwagger({
				routePrefix: '/swagger',
				swaggerOptions: {
					url: '/swagger.json',
				},
			})
		))

// 报错返回错误
app.use(
	error({
		postFormat: (e, { stack, ...rest }) =>
			process.env.NODE_ENV === 'production' ? rest : { stack, ...rest },
	})
)
// 限流
// const db = new Map()
// app.use(ratelimit({
//     driver: 'memory',
//     db: db,
//     duration: 60000,
//     errorMessage: '请求过于频繁，请稍后再试。',
//     id: (ctx) => ctx.ip,
//     headers: {
//       remaining: 'Rate-Limit-Remaining',
//       reset: 'Rate-Limit-Reset',
//       total: 'Rate-Limit-Total'
//     },
//     max: 3,
//     disableHeader: false,
//     whitelist: (ctx) => {
//         console.log('whitelist',ctx.url)
//       // some logic that returns a boolean
//     },
//     blacklist: (ctx) => {
//         console.log('blacklist',ctx.url)

//       // some logic that returns a boolean
//     }
//   }));
// 取消jwt检查接口

// jwt 鉴权配置
app.use((ctx, next) => {
	return next().catch((err) => {
		if (err.status === 401) {
			ctx.status = 200
			ctx.body = {
				code: 747,
				msg: '未登录，请先登录后操作',
			}
		} else {
			throw err
		}
	})
})
app.use(
	jwtKoa(jwtConfig).unless({
		path: [
			/\/api\/token/,
			/\/jinritemai\/*/,
			// /\/web\/*/,
			/\/api\/user\/shopLogin/,
			/\/dlyadminapi\/addAdminUser/,
			// /\/dlyadminapi\/registry/,
			/\/dlyadminapi\/login/,
			/\/dlyadminapi\/link\/binduser\/*/,
			/\/dlyadminapi\/link\/saveUserProxy/,
			/\/api\/tools\/statisticsDowAppNum/,
			/\/api\/tools\/statisticsJupAotoTkNum/,
			/\/api\/tools\/savePageCI/,
			/\/api\/tools\/savePlginOssPath/,
			/\/api\/tools\/getPlginOssPath/,
			/\/api\/zhangfuai\/aiRspRs/,
			/\/api\/alipay\/cb/,
			/\/api\/aiuser\/code/,
			/\/api\/dlyuser\/code/,
			/\/api\/aiuser\/creted/,
			/\/api\/dlyuser\/creted/,
			/\/api\/aiuser\/refreshLogin/,
			/\/api\/dlyuser\/refreshLogin/,
			/\/api\/test\/*/,
			// /\/dlyadminapi\/material\/*/
		], // /\/api\/user/,
	})
)

// 静态文件
app.use(koaStatic(path.join(__dirname, '/public')))

// 解析post请求 文件上传 from-data
app.use(
	koaBody({
		text: true,
		json: true,
		multipart: true,
		urlencoded: true,
		formidable: {
			uploadDir: path.join(__dirname, '/public/uploads'),
			keepExtensions: true,
		},
		jsonLimit: '10mb',
		textLimit: '10mb',
		formLimit: '10mb',
	})
)

// 运行日志
app.use(logger())

// 返回值中间件
app.use(responseFilter())

/**
 *  字段检查中间件
 *  ctx.verifyParams({
 *      code: {type: 'string', required: true}
 *  })
 */

app.use(parameter(app))

app.use(adminUser())

/**
 * 检查查询的用户的shop_id
 * @param [apiurl ... ]
 */
app.use(cheackShop([/\/web\/*/, /\/api\/rights\/*/]))

// 检查aiuser接口
app.use(cheackAiUser())

// 添加路由routes
routing(app)
// app.use(index.routes()).use(index.allowedMethods())
// app.use(user.routes()).use(user.allowedMethods())

export default app
